<script setup>
import { ref } from 'vue';
import { getAppointmentByDate, updateAppointment } from '@/api/appointment';
import { useUserInfoStore } from '@/stores/userInfo.js';
import { userInfoGetService } from '@/api/user.js';
import { ElMessage } from 'element-plus';
import { getAllDoctorsService, getPatientByIdService } from '@/api/admin.js';

const userInfoStore = useUserInfoStore();
const appointmentList = ref([]);
const patientList = ref([]);
const doctorId = ref(null); // 使用单独的响应式变量存储医生ID

// 获取医生信息
const getDoctorInfo = async () => {
    try {
        const result = await getAllDoctorsService();
        const doctor = result.data.find(d => d.username === userInfoStore.info.username);
        if (doctor) {
            doctorId.value = doctor.doctorId;
        }
    } catch (error) {
        ElMessage.error('获取医生信息失败');
    }
};

// 获取预约列表
const getAppointmentList = async () => {
    try {
        // 清空旧数据
        appointmentList.value = [];
        patientList.value = [];
        
        const result = await getAppointmentByDate();
        
        // 筛选当前医生的预约
        const filteredAppointments = result.data.filter(
            appointment => appointment.doctorId === doctorId.value
        );
        
        // 处理预约数据
        for (const appointment of filteredAppointments) {
            appointmentList.value.push(appointment);
            // 获取患者信息
            const patientRes = await getPatientByIdService(appointment.patientId);
            patientList.value.push(patientRes.data);
        }
    } catch (error) {
        ElMessage.error('获取预约列表失败');
    }
};

// 获取用户信息
const getUserInfo = async () => {
    try {
        const result = await userInfoGetService();
        userInfoStore.setInfo(result.data);
    } catch (error) {
        ElMessage.error('获取用户信息失败');
    }
};

// 处理叫号操作
const handleUpdate = (row) => {
    if (row.status === '已叫号') {
        ElMessage.error('该预约已叫号，请勿重复操作');
        return;
    }
    
    updateAppointment({ 
        appointmentId: row.appointmentId, 
        status: '已叫号' 
    }).then(() => {
        ElMessage.success('叫号成功');
        // 更新本地数据（无需重新获取整个列表）
        const index = appointmentList.value.findIndex(
            item => item.appointmentId === row.appointmentId
        );
        if (index !== -1) {
            appointmentList.value[index].status = '已叫号';
        }
    }).catch(error => {
        ElMessage.error('叫号失败');
    });
};

// 行样式
const rowStyle = (row) => {
    return row.status === '已叫号' ? { background: 'lightgreen' } : {};
};

// 初始化
getUserInfo();
getDoctorInfo();
</script>

<template>
    <el-container>
        <el-header>
            <el-button type="primary" @click="getAppointmentList">获取今日预约列表</el-button>
        </el-header>
        <el-main>
            <el-table 
                :data="appointmentList" 
                style="width: 100%"
                :row-style="rowStyle"
            >
                <el-table-column
                    label="序号"
                    type="index"
                    width="50"
                />
                <el-table-column prop="appointmentTime" label="预约时间" />
                <el-table-column label="患者姓名">
                    <template #default="{ $index }">
                        {{ patientList[$index]?.name || '未知' }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" />
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button 
                            type="primary" 
                            @click="handleUpdate(scope.row)"
                            :disabled="scope.row.status === '已叫号'"
                        >
                            {{ scope.row.status === '已叫号' ? '已叫号' : '叫号' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
    </el-container>
</template>

<style scoped>
.el-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
}
</style>